/*
 * @Author: your name
 * @Date: 2022-02-28 11:17:12
 * @LastEditTime: 2022-04-24 20:50:39
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \blog-system-front\src\Pages\User\UserInfo.js
 */
import React, { useState } from "react";
import {
  Form,
  Input,
  Divider,
  Card,
  Select,
  Row,
  message,
  Checkbox,
  Button,
  Upload,
  notification,
  Space,
} from "antd";
import { useSelector } from "react-redux";
import request from "../../api";
import ContentHeader from "../../Containers/ContentHeader";
import Main from "../../Containers/main";
import { connect } from "react-redux";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
function UserInfo(props) {
  const formItemLayout = {
    labelCol: {
      xs: {
        span: 12,
      },
      sm: {
        span: 5,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 16,
      },
    },
  };

  const [form] = Form.useForm();
  const user = useSelector((state) => state.user);
  const [picUrl, setPicurl] = useState(user.picUrl);
  const [edit, setEdit] = useState(false);
  form.setFieldsValue({
    username: user.username,
    nickname: user.nickname,
    realname: user.realname,
    sex: user.sex,
    email: user.email,
    area: user.area,
    telphone: user.telphone,
    picUrl: picUrl,
  });
  const onFinish = (fieldsValue) => {
    const data = {
      ...fieldsValue,
      userId: user.userId,
      picUrl,
    };
    request({
      method: "POST",
      url: "v1/update/userlist",
      data,
    }).then((res) => {
      if (res) {
        notification.success({
          message: "修改成功",
        });
        setEdit(false);
        props.dispatch({
          type: "USER_FETCH_REQUESTED",
        });
      }
    });
  };
  function beforeUpload(file) {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  }
  const handleFileChange = (file) => {
    const { response, status } = file.file;
    if (status === "done") {
      setPicurl(response.url);
    }
  };

  const buttonItemLayout = { wrapperCol: { span: 14, offset: 4 } };
  return (
    <>
      <ContentHeader title="个人中心">
        <Button type="primary" onClick={() => setEdit(true)}>
          个人资料更新
        </Button>
      </ContentHeader>
      <Main>
        <Card title="基本信息">
          <Form
            {...formItemLayout}
            form={form}
            onFinish={onFinish}
            style={{
              margin: "0 auto",
            }}
          >
            <Form.Item name="picUrl" label="头像">
              {edit ? (
                <Upload
                  name="file"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  action="http://106.15.45.34:5000/v1/file-upload"
                  beforeUpload={beforeUpload}
                  headers={{
                    Authorization: `bearer ${localStorage.getItem("token")}`,
                  }}
                  onChange={handleFileChange}
                  data={{ userId: user.userId, picUrl: user.picUrl }}
                >
                  {picUrl ? (
                    <img src={picUrl} alt="avatar" style={{ width: "100%" }} />
                  ) : (
                    <div>
                      {<PlusOutlined />}
                      <div style={{ marginTop: 8 }}>Upload</div>
                    </div>
                  )}
                </Upload>
              ) : (
                <img src={picUrl} style={{ width: "20%", height: "20%" }}></img>
              )}
            </Form.Item>

            <Form.Item name="username" label="用户名">
              {edit ? <Input disabled /> : <span>{user.username}</span>}
            </Form.Item>
            <Form.Item
              name="telphone"
              label="电话号码"
              rules={[
                {
                  pattern:
                    /^134[0-8]\d{7}$|^13[^4]\d{8}$|^14[5-9]\d{8}$|^15[^4]\d{8}$|^16[6]\d{8}$|^17[0-8]\d{8}$|^18[\d]{9}$|^19[8,9]\d{8}$/,
                  message: "请输入手机号",
                },
              ]}
            >
              {edit ? <Input /> : <span>{user.telphone}</span>}
            </Form.Item>
            <Form.Item name="nickname" label="昵称">
              {edit ? <Input /> : <span>{user.nickname}</span>}
            </Form.Item>
            <Form.Item name="realname" label="真实姓名">
              {edit ? <Input /> : <span>{user.realname}</span>}
            </Form.Item>
            <Form.Item name="sex" label="性别">
              {edit ? (
                <Select>
                  <Select.Option value="male">男</Select.Option>
                  <Select.Option value="famale">女</Select.Option>
                </Select>
              ) : (
                <span>{user.sex === "male" ? "男": "女"}</span>
              )}
            </Form.Item>
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                {
                  type: "email",
                  message: "请输入有效的邮箱",
                },
              ]}
            >
              {edit ? <Input /> : <span>{user.email}</span>}
            </Form.Item>
            <Form.Item name="area" label="地区">
              {edit ? <Input /> : <span>{user.area}</span>}
            </Form.Item>
            <Form.Item {...buttonItemLayout}>
              {edit && (
                <Space>
                  <Button type="primary" htmlType="submit">
                    保存
                  </Button>
                  <Button type="primary" onClick={() => setEdit(false)}>
                    取消
                  </Button>
                </Space>
              )}
            </Form.Item>
          </Form>
        </Card>
      </Main>
    </>
  );
}
export default connect()(UserInfo);
